from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from order import models,ser
from rest_framework.response import Response
from rest_framework.filters import SearchFilter
from cart.models import CartModel
from cart.ser import CartService
import random

from utils.Alipay import AliPaySDK


# Create your views here.

class AddressViewSet(ModelViewSet):
    queryset = models.AddressModel.objects.all()
    serializer_class = ser.AddressSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"
    filter_backends = [SearchFilter]
    search_fields = ['name','phone','address']

import time
def get_order_number():
    order_number = str(time.strftime("%Y%m%d%H%M%S"))+str(random.randint(1000,9999))
    return order_number
class ADDOrderView(APIView):
    def post(self, request):
        try:
            order = get_order_number()
            data = request.data
            time = data.get('time')
            address_id = data.get('address')
            user_id = int(data.get('user'))
            invoice = data.get('invoice')
            price = int(data.get('price'))
            amount = data.get('amount')
            zf = data.get('zf')
            if time is None:
                return Response({'message': '请选择配送时间', 'code': 400})
            if address_id is None:
                return Response({'message': '请选择配送地址', 'code': 400})
            if user_id is None:
                return Response({'message': '请先登录', 'code': 400})
            if zf is None:
                return Response({'message': '请选择支付方式', 'code': 400})
            existing_data = models.OrderModel.objects.filter(order=order)
            if existing_data.exists():
                return Response({'message': '该订单已存在', 'code': 400})
            else:
                models.OrderModel.objects.create(
                    order=order, time=time, address_id=address_id, user_id=user_id, invoice=invoice,
                    price=price, amount=amount, zf=zf
                )
                return Response({'message': '下单成功', 'code': 200 ,"orderno":order})
        except Exception as e:
            return Response({'message': f'出现错误: {str(e)}', 'code': 500})
class AllOrderView(APIView):
    def get(self, request):
        user_id=request.GET.get('user')
        data = CartModel.objects.filter(user_id=user_id,isshow=True)
        Ser = CartService(instance=data, many=True)
        return Response(Ser.data)

class OrderView(APIView):
    def post(self, request):
        orderno=request.data.get('orderno')
        data=models.OrderModel.objects.filter(order=orderno)
        Ser = ser.OrderSerializer(instance=data, many=True)
        return Response(Ser.data)

class CakedOrderView(APIView):
    def get(self, request):
        data = CartModel.objects.filter(isshow=True)
        Ser = CartService(instance=data, many=True)
        return Response(Ser.data)
# 支付
class PayView(APIView):
    def get(self, request):
        try:
            # 获取并验证订单 ID
            id_str = request.GET.get('id')
            if id_str is None:
                return Response({"msg": "缺少订单 ID 参数", "code": 400})
            id = int(id_str)

            # 查询订单信息
            data = models.OrderModel.objects.filter(id=id).first()
            if data is None:
                return Response({"msg": "未找到对应的订单", "code": 404})

            # 初始化支付实例
            Pay = AliPaySDK()
            url = Pay.page_pay(data.order, data.amount, "畅乐福商品支付")

            if url:
                # 删除购物车记录，处理 ret 为 None 的情况
                ret = models.CartModel.objects.filter(isshow=True).first()
                if ret:
                    ret.delete()

                return Response({"url": url, "msg": "正在拉起支付链接", "code": 200})
            else:
                return Response({"msg": "支付链接生成失败", "code": 500})

        except ValueError:
            return Response({"msg": "订单 ID 必须是有效的整数", "code": 400})
        except Exception as e:
            return Response({"msg": f"发生未知错误: {str(e)}", "code": 500})